const User = require('../models/User');
const Job = require('../models/job');
const Application = require('../models/Application');
const Announcement = require('../models/Announcement');
const Company = require('../models/company');
const SystemLog = require('../models/SystemLog');
const sequelize = require('../config/database');

const { Op } = require('sequelize');
const { sendAnnouncementNotification } = require('../services/notification.service');

// 管理员获取系统统计数据
exports.getSystemStats = async (req, res) => {
  try {
    // 用户统计
    const userStats = await User.count({
      group: ['role', 'status'],
      where: { role: { [Op.ne]: 'admin' } }
    });

    // 职位统计
    const jobStats = await Job.count({
      group: ['status', 'industry']
    });

    // 申请统计
    const applicationStats = await Application.count({
      group: ['status']
    });

    // 日期范围统计
    const dateRangeStats = await Application.findAll({
      attributes: [
        [sequelize.fn('DATE_FORMAT', sequelize.col('createdAt'), '%Y-%m-%d'), 'date'],
        [sequelize.fn('COUNT', sequelize.col('id')), 'count']
      ],
      where: {
        createdAt: {
          [Op.gte]: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000) // 近30天
        }
      },
      group: ['date']
    });

    res.status(200).json({
      success: true,
      data: {
        users: userStats,
        jobs: jobStats,
        applications: applicationStats,
        recentApplications: dateRangeStats
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取统计数据失败',
      error: error.message
    });
  }
};

// 管理员发布系统公告
exports.createAnnouncement = async (req, res) => {
  try {
    const { title, content, userIds } = req.body;

    const announcement = await Announcement.create({
      title,
      content,
      createdBy: req.user.id,
      publishDate: new Date()
    });

    // 发送公告通知
    await sendAnnouncementNotification({
      title,
      content,
      userIds
    });

    res.status(201).json({
      success: true,
      message: '公告发布成功',
      data: announcement
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '发布公告失败',
      error: error.message
    });
  }
};

// 管理员获取所有公告
exports.getAllAnnouncements = async (req, res) => {
  try {
    const announcements = await Announcement.findAll({
      order: [['publishDate', 'DESC']],
      include: ['author']
    });

    res.status(200).json({
      success: true,
      data: announcements
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取公告列表失败',
      error: error.message
    });
  }
};

// 管理员审核企业账号
exports.reviewCompany = async (req, res) => {
  try {
    const { id, status, feedback } = req.body;

    const company = await Company.findByPk(id);
    if (!company) {
      return res.status(404).json({
        success: false,
        message: '企业不存在'
      });
    }

    await company.update({
      status,
      reviewFeedback: feedback,
      reviewedAt: new Date(),
      reviewerId: req.user.id
    });

    // 更新关联用户状态
    await User.update(
      { status: status === 'approved' ? 'active' : 'inactive' },
      { where: { id: company.userId } }
    );

    res.status(200).json({
      success: true,
      message: '企业审核完成',
      data: company
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '审核企业失败',
      error: error.message
    });
  }
};

// 获取待审核企业列表
exports.getPendingCompanies = async (req, res) => {
  try {
    const companies = await Company.findAll({
      where: { status: 'pending' },
      include: ['user']
    });

    res.status(200).json({
      success: true,
      data: companies
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取待审核企业失败',
      error: error.message
    });
  }
};

// 管理员获取系统日志
exports.getSystemLogs = async (req, res) => {
  try {
    const { page = 1, limit = 20 } = req.query;
    const offset = (page - 1) * limit;

    const { count, rows: logs } = await SystemLog.findAndCountAll({
      limit: parseInt(limit),
      offset: parseInt(offset),
      order: [['createdAt', 'DESC']]
    });

    res.status(200).json({
      success: true,
      data: {
        logs,
        pagination: {
          total: count,
          page: parseInt(page),
          limit: parseInt(limit),
          pages: Math.ceil(count / limit)
        }
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取系统日志失败',
      error: error.message
    });
  }
};